/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package todomanager.View;

/**
 *
 * @author Gi-Hoon
 * @author Jonas Birgersson
 */
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableColumnModel;

import todomanager.MODEL.TodoManagerModel;

public class MainFrame extends JFrame implements ComponentListener {

	// Window minimum size
	private final static int MIN_WIDTH = 550;
	private final static int MIN_HEIGHT = 250;
	
	private String currentThemeName;

	private AddFrameView addView;
	private EditFrame editView;
	private AboutView aboutView;

	private ResourceBundle language;
	private Properties appProperties;

	private JButton buttonAdd;
	private JButton buttonEdit;
	private JButton buttonDelete;
	private LedTimer ledTimer = new LedTimer(100, 40, true);

	private JTable mainTable = new JTable(
			new Object[][] { { null, null, null, null, null },
					{ null, null, null, null, null },
					{ null, null, null, null, null },
					{ null, null, null, null, null } }, new String[] { "Done",
					"Priority", "Category", "Date", "Name" });

	private JTextArea description = new JTextArea(3, 20);

	private JPanel panelButton = new JPanel(new FlowLayout(FlowLayout.RIGHT));
	private JPanel panelClock = new JPanel(new FlowLayout(FlowLayout.LEFT));
	private JPanel panelBottom = new JPanel(new GridLayout(1, 2));
	private JPanel panel_component = new JPanel(new GridLayout(0, 1));

	private JPanel panelCenter = new JPanel(new BorderLayout());

	private JMenuBar menuBar = new JMenuBar();
	private JMenu menuFile = new JMenu();
	private JMenu menuEdit = new JMenu();
	private JMenu menuThemes = new JMenu();	
	private JMenu menuHelp = new JMenu();

	private JMenuItem menuFileItemQuit;

	private JMenuItem menuEditItemAdd;
	private JMenuItem menuEditItemEdit;
	private JMenuItem menuEditItemDelete;
	
	private JCheckBoxMenuItem menuThemeItemUgly;
	private JCheckBoxMenuItem menuThemeItemTest;	

	private JMenuItem menuHelpItemAbout;

	private TodoManagerModel todoModel;

	private MainTable tableView;

	ProgressCellRenderer progressbar = new ProgressCellRenderer(0, 100);

	public MainFrame(TodoManagerModel todoModel, ResourceBundle lang) {
		try {
			this.todoModel = todoModel;
			tableView = new MainTable(todoModel, lang);
			this.language = lang;
			this.addView = new AddFrameView(lang);
			this.editView = new EditFrame(lang);
			this.aboutView = new AboutView();
			Mframe();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void Mframe() throws Exception {

		// Load application settings from file!

		getProperties();

		this.setLayout(new BorderLayout());



		// TODO: should we delete below?
		// JScrollPane scrollPane = new JScrollPane(maintable);
		// maintable.setFillsViewportHeight(true);

		// Description field
		JScrollPane scrollPane = new JScrollPane(description);
		description.setEditable(false);

		TitledBorder title_description;
		title_description = BorderFactory.createTitledBorder(getLabel("DescriptionLabel"));
		description.setBorder(title_description);

		// Add clockLabel to container panelClock && add panelClock to
		// panelBottom
		panelClock.add(ledTimer);

		panelBottom.add(panelClock);
		panelBottom.add(panelButton);

		// Add panelBottom to the bottom(south) of the MainFrame
		this.add("South", panelBottom);

		// progress bar in table
		progressbar.setStringPainted(true);
		progressbar.setBackground(tableView.getTable().getBackground());
		tableView.getTable().getColumnModel().getColumn(6)
				.setCellRenderer(progressbar);

		// check box in table
		tableView.getTable().getColumnModel().getColumn(0)
				.setCellRenderer(new CheckBoxCellRenderer());

		// Add Table Elements
		panelCenter.add("Center", tableView);

		// Add description and progress Elements
		panel_component.add(description);

		panelCenter.add("South", panel_component);

		// panelCenter.add("South", description);
		this.add("Center", panelCenter);

		// Setup menu bar
		menuFile.setText(this.getLabel("menuFile"));
		menuEdit.setText(this.getLabel("menuEdit"));
		menuThemes.setText(this.getLabel("menuThemes"));		
		menuHelp.setText(this.getLabel("menuHelp"));

		menuBar.add(menuFile);
		menuBar.add(menuEdit);
		menuBar.add(menuThemes);		
		menuBar.add(menuHelp);

		this.setJMenuBar(menuBar);

		// exit from the program when this fram is closed
		setDefaultCloseOperation(EXIT_ON_CLOSE);

		// Initialize Add View
		addView.setLocation(100, 100);
		addView.setVisible(false);

		// Initialize edit View
		editView.setLocation(100, 100);
		editView.setVisible(false);

		// Edit Progress Slider & Description field
		tableView.getTable().getSelectionModel()
				.addListSelectionListener(new ListSelectionListener() {
					public void valueChanged(ListSelectionEvent event) {
						int viewRow = tableView.getTable().getSelectedRow();
						if (viewRow < 0) {
							// Selection got filtered away.
							System.out.println("");
						} else {
							description.setText((String) tableView.getTable()
									.getValueAt(viewRow, 2));
						}
					}
				});

		// Start the LED Timer
		this.ledTimer.start();

		// Add component Listener
		this.addComponentListener(this);

	}

	private void getProperties() throws IOException {
		Properties appProperties = new Properties();
		FileInputStream fis = new FileInputStream("todo.properties");
		appProperties.load(fis);

		this.setLocation(
				new Integer(appProperties.getProperty("mainWindowXPos"))
						.intValue(),
				new Integer(appProperties.getProperty("mainWindowYPos"))
						.intValue());
		this.setSize(new Integer(appProperties.getProperty("mainWindowWidth"))
				.intValue(),
				new Integer(appProperties.getProperty("mainWindowHeight"))
						.intValue());

		this.getAddView()
				.setLocation(
						new Integer(appProperties.getProperty("addWindowXPos"))
								.intValue(),
						new Integer(appProperties.getProperty("addWindowYPos"))
								.intValue());

		this.getAddView()
				.setSize(
						new Integer(appProperties.getProperty("addWindowWidth"))
								.intValue(),
						new Integer(appProperties
								.getProperty("addWindowHeight")).intValue());
		this.getEditView()
				.setLocation(
						new Integer(appProperties.getProperty("editWindowXPos"))
								.intValue(),
						new Integer(appProperties.getProperty("editWindowYPos"))
								.intValue());
		this.getEditView()
				.setSize(
						new Integer(appProperties.getProperty("editWindowWidth"))
								.intValue(),
						new Integer(appProperties
								.getProperty("editWindowHeight")).intValue());

		fis.close();
		// TODO Auto-generated method stub

	}

	public void updateTableData() {
		tableView.refreshTable();

	}

	public void setAddFrameVisiblity(boolean value) {
		this.addView.setVisible(value);
	}

	public AddFrameView getAddView() {
		return this.addView;
	}

	public void seteditFrameVisiblity(boolean value) {
		this.editView.setVisible(value);
	}

	public EditFrame getEditView() {
		return this.editView;
	}

	public void addMenuActions(Action quitAction, Action addAction,
							   Action editTaskAction, Action deleteTaskAction,
							   Action showAboutAction,
							   Action selectUglyThemeAction, Action selectTestThemeAction) {
		this.menuFileItemQuit = new JMenuItem(quitAction);
		this.menuFile.add(this.menuFileItemQuit);

		this.menuEditItemAdd = new JMenuItem(addAction);
		this.menuEdit.add(this.menuEditItemAdd);

		this.menuEditItemEdit = new JMenuItem(editTaskAction);
		this.menuEdit.add(this.menuEditItemEdit);

		this.menuEditItemDelete = new JMenuItem(deleteTaskAction);
		this.menuEdit.add(this.menuEditItemDelete);
		
		this.menuThemeItemTest = new JCheckBoxMenuItem(selectTestThemeAction);
		if(this.currentThemeName.equals("testtheme")) {
			this.menuThemeItemTest.setSelected(true);
		}
		
		this.menuThemeItemUgly = new JCheckBoxMenuItem(selectUglyThemeAction);
		if(this.currentThemeName.equals("uglytheme")) {
			this.menuThemeItemUgly.setSelected(true);
		}
		
		ButtonGroup bg = new ButtonGroup();
		bg.add(this.menuThemeItemUgly);
		bg.add(this.menuThemeItemTest);		
		
		this.menuThemes.add(this.menuThemeItemTest);		
		this.menuThemes.add(this.menuThemeItemUgly);

		this.menuHelpItemAbout = new JMenuItem(showAboutAction);
		this.menuHelp.add(this.menuHelpItemAbout);

	}

	public void addButtonActions(Action addAction, Action editAction,
			Action deleteAction) {
		this.buttonAdd = new JButton(addAction);
		this.panelButton.add(this.buttonAdd);

		this.buttonEdit = new JButton(editAction);
		this.panelButton.add(this.buttonEdit);

		this.buttonDelete = new JButton(deleteAction);
		this.panelButton.add(this.buttonDelete);
	}

	public void addDeleteAction(Action deleteAction) {
		this.buttonDelete.addActionListener(deleteAction);
	}

	public int getSelectedRowInTable() {
		return tableView.getSelectedRow();
	}

	public int getSelectedTaskKey() {
		return tableView.getKey(tableView.getSelectedRow());

	}

	public void setLanguageResource(ResourceBundle lang) {
		this.language = lang;
	}

	public String getLabel(String labelName) {
		return this.language.getString(labelName);
	}

	public void showAboutFrame() {
		this.aboutView.setVisible(true);

	}

	@Override
	public void componentHidden(ComponentEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void componentMoved(ComponentEvent arg0) {
		// TODO Auto-generated method stub

	}

	/**
	 * Resizes the window back to it's minimum size if it's to small.
	 */
	@Override
	public void componentResized(ComponentEvent arg0) {
		int width = this.getWidth();
		int height = this.getHeight();
		if (width < MIN_WIDTH) {
			this.setSize(MIN_WIDTH, height);
		}
		if (height < MIN_HEIGHT) {
			this.setSize(width, MIN_HEIGHT);
		}
		// TODO Auto-generated method stub

	}

	@Override
	public void componentShown(ComponentEvent arg0) {
		// TODO Auto-generated method stub

	}
	
	public void setCurrentTheme(String themeName) {
		this.currentThemeName = themeName;
	}
	
	public String getCurrentTheme() {
		return this.currentThemeName;
	}

	public String getSelectedTaskName() {
		return tableView.getName();
	}

}